$(function () {
    regValidate(["#mainForm"]);
    initTextSearch("#pDeptName",basePath + 'basicDoctorInfo/getPDeptList?t='+ (new Date()).getTime()+'&name=',['deptCode','deptName'],{'deptCode':'科室编码','deptName':'科室名称'},'deptCode','deptName',true,selectPDeptValue,pDeptChange);
    initTextSearchWithParam("#cDeptName",basePath + 'basicDoctorInfo/getCDeptList?t='+ (new Date()).getTime(),['deptCode','deptName'],{'deptCode':'科室编码','deptName':'科室名称'},'deptCode','deptName',true,selectCDeptValue,cDeptChange,getPDeptCode);
    initTextSearch("#orgName",basePath + 'basicDoctorInfo/getOrgList?t='+ (new Date()).getTime()+'&name=',['orgName','orgCode'],{'orgName':'机构名称','orgCode':'编码'},'orgCode','orgName',true,selectOrgValue,orgChange);
    initTextSearch("#isvPidName",basePath + 'basicDoctorInfo/getIsvList?t='+ (new Date()).getTime()+'&name=',['isvPid','isvName'],{'isvPid':'isvPid','isvName':'服务商名称'},'isvPid','isvName',true,selectIsvValue,isvChange);
    if(oneBasicDoctorInfo && oneBasicDoctorInfo.certificateMedia){
        console.log(oneBasicDoctorInfo.certificateMedia);
        var certificateMedias = oneBasicDoctorInfo.certificateMedia.split(',');
        if(certificateMedias[0]){
            $("#coverUrlImg2").attr("src", certificateMedias[0]);
        }
        if(certificateMedias[1]){
            $("#coverUrlImg3").attr("src", certificateMedias[1]);
        }
        if(certificateMedias[2]){
            $("#coverUrlImg4").attr("src", certificateMedias[2]);
        }
    }
});

function doBack() {
    var data = getFromData("#mainForm");
    data.docLogo = $("#docLogo").val()?$("#docLogo").val():$("#docLogoHidden").val();
    if (type != 'info' &&(!Compare(data, oneBasicDoctorInfo)||$("#coverUrlFile1").val()!= ''||$("#coverUrlFile2").val()!= ''||$("#coverUrlFile3").val()!= ''||$("#coverUrlFile4").val()!= '')) {  //判断图片
        swal({
            title:"提示",
            text:common_no_save_msg,
            showCancelButton:true,
            showConfirmButton:true,
            confirmButtonText:"确定",
            cancelButtonText:"取消",
            animation:"slide-from-top"
        }, function() {
            goBack();
        });
        return;
    }
    goBack();
}

function goBack() {
    var str = '&docName=' + searchInfo.docName + '&isvPid=' + searchInfo.isvPid + '&isvName=' + searchInfo.isvName
        + '&status=' + searchInfo.status + '&dataStatus=' + searchInfo.dataStatus + '&docMediLevel=' + searchInfo.docMediLevel
        + '&pDeptCode=' + searchInfo.pDeptCode + '&pDeptName=' + searchInfo.pDeptName + '&cDeptCode=' + searchInfo.cDeptCode
        + '&cDeptName=' + searchInfo.cDeptName + '&orgCode=' + searchInfo.orgCode + '&orgName=' + searchInfo.orgName
        + '&isMerge=' + searchInfo.isMerge + '&pageNo=' + searchInfo.pageNo + '&pageSize=' + searchInfo.pageSize;
    window.location.href = basePath + 'basicDoctorInfo/page?t=' + new Date().getTime() + str;
}

function doSave(){
    if(!$("#mainForm").valid()) return;//校验不通过
    /*fileCheck("coverUrlFile1", "coverUrlImg1", 1024*10, 80, 80, "您上传的图片大小超出限制范围（10k以内），无法上传，请重新上传符合要求的图片！",
        "您上传的图片尺寸不符合要求（80*80px），可能会影响APP展示效果，是否继续保存？", saveNextPic1);*/

    var idList = ['coverUrlFile1', 'coverUrlFile2', 'coverUrlFile3', 'coverUrlFile4'];
    var sizeList = [1024*40, 1024*60, 1024*60, 1024*60];
    var msgList = ["您上传的图片【头像】大小超出限制范围（10k以内），无法上传，请重新上传符合要求的图片！", "您上传的图片【证书照片1】大小超出限制范围（60k以内），无法上传，请重新上传符合要求的图片！", "您上传的图片【证书照片2】大小超出限制范围（60k以内），无法上传，请重新上传符合要求的图片！", "您上传的图片【证书照片3】大小超出限制范围（60k以内），无法上传，请重新上传符合要求的图片！"];
    //filesSizeCheck(idList, sizeList, msgList, checkFileChiCun);
    existDoc();
}

function checkFileChiCun() {
    var imageList = [];
    var image1 = {
        imageName : '头像',
        fileId: 'coverUrlFile1',
        imageId : 'coverUrlImg1',
        fileWidth : 80,
        fileHeight : 80,
    };
    imageList.push(image1);
    filesChiCunCheck(imageList, existDoc);
}

function existDoc(){
    var data = getFormData("#mainForm");
    var dataStr = JSON.stringify(data);
    $.ajax({
        type: 'post',
        url:basePath + 'basicDoctorInfo/countPivDoc',
        dataType: 'json',
        contentType: "application/json",
        data: dataStr,
        success: function (data) {
            if (!data.isSuccess) {
                swal({
                    title:"提示",
                    text:'您上传的医生已存在,是否继续上传?',
                    type:"warning",
                    showCancelButton:"true",
                    showConfirmButton:"true",
                    confirmButtonText:"确定",
                    cancelButtonText:"取消",
                    animation:"slide-from-top"
                }, function() {});
            } else {
                saveFun();
            }
        },
        error: function (request) {
            toastr.error(common_system_error);
        }});
}

/*function saveNextPic1() {
    setTimeout(function () {
        fileCheck("coverUrlFile2", "coverUrlImg2", 1024*60, null, null, "您上传的图片大小超出限制范围（60k以内），无法上传，请重新上传符合要求的图片！",
            null, saveNextPic2);
    }, 1000);
}

function saveNextPic2() {
    setTimeout(function () {
        fileCheck("coverUrlFile3", "coverUrlImg3", 1024*60, null, null, "您上传的图片大小超出限制范围（60k以内），无法上传，请重新上传符合要求的图片！",
            null, saveNextPic3);
    }, 1000);
}

function saveNextPic3() {
    setTimeout(function () {
        fileCheck("coverUrlFile4", "coverUrlImg4", 1024*60, null, null, "您上传的图片大小超出限制范围（60k以内），无法上传，请重新上传符合要求的图片！",
            null, saveFun);
    }, 1000);
}*/

function saveFun() {
    var data=getFormData("#mainForm");
    var url = basePath + 'basicDoctorInfo/insertBasicDoctorInfo?t='+new Date().getMilliseconds();
    if (type == 'edit') {
        url = basePath + 'basicDoctorInfo/editBasicDoctorInfo?t='+new Date().getMilliseconds();
    }
    showLoading();
    $.ajaxFileUpload({
        url : url,
        type : "post",
        secureuri : false,
        fileElementId : ["coverUrlFile1", "coverUrlFile2", "coverUrlFile3", "coverUrlFile4"],
        dataType : "json",
        data : data,
        success : function (data) {
            hideLoading();
            if(data && data.isSuccess){
                toastr.success(common_save_success);
                goBack();
            }else if(data&&!data.isSuccess){
                toastr.error(data.errorDesc?data.errorDesc:common_save_fail);
            }
        },
        error: function (request) {
            toastr.error(common_system_error);
        }
    });
}

function pDeptChange() {
    //清空值
    $('#pDeptCode').val("");
    //修改一级时，清空二级
    $('#cDeptCode').val("");
    $('#cDeptName').val("");
}

function selectPDeptValue(data) {
    //联动赋值
    if (data && data.deptCode && data.deptCode != '') {
        $('#pDeptCode').val(data.deptCode);
        //修改一级时，清空二级
        $('#cDeptCode').val("");
        $('#cDeptName').val("");
    }
}

function cDeptChange() {
    //清空值
    $('#cDeptCode').val("");
}

function selectCDeptValue(data) {
    //联动赋值
    if (data && data.deptCode && data.deptCode != '') {
        $('#cDeptCode').val(data.deptCode);
    }
}

function getPDeptCode(){
    var pDeptCode = $('#pDeptCode').val();
    return {
        t: new Date().getTime(),
        name: $('#cDeptName').val(),
        parentCode: pDeptCode
    };
}

function orgChange() {
    //清空值
    $('#orgCode').val("");
}

function selectOrgValue(data) {
    //联动赋值
    if (data && data.orgCode && data.orgCode != '') {
        $('#orgCode').val(data.orgCode);
    }
}

function isvChange() {
    //清空值
    $('#isvPid').val("");
}

function selectIsvValue(data) {
    //联动赋值
    if (data && data.isvPid && data.isvPid != '') {
        $('#isvPid').val(data.isvPid);
    }
}

function onPreviewUrl(obj, previewId) {
    if(obj && obj.value){
        $("#" + previewId).attr("src", obj.value);
    }
}